#ifndef _KC_LDAPCONNECTION_H__KC_
#define _KC_LDAPCONNECTION_H__KC_

#include <iostream>
#include <ldap.h>

#ifndef LDAP_DEPRECATED
#define LDAP_DEPRECATED
#endif

namespace kc_sf
{

	int search()
	{
		LDAPMessage *searchResult;
		char *attribute, **values;
		struct timeval timeOut = { 10, 0 }; // 10 second connecion/search timeout

		ldap_set_option( NULL, LDAP_OPT_PROTOCOL_VERSION, &LDAP_VERSION3 );

		LDAP *ld;
	    ldap_initialize( &ld, "ldap://localhost:389" );

	    struct BerValue credentials;
	    std::string admin_passwd = "secret";
	    credentials.bv_val = admin_passwd.c_str();
	    credentials.bv_len = admin_passwd.size() + 1;
	    struct BerValue *server_cred;
	    int rc = ldap_sasl_bind_s( ld, NULL, NULL, &credentials, NULL, NULL, &server_cred );

		//rc = ldap_simple_bind_s( ld, "cn=admin,o=acme", "acmeadminpassword" );

		if ( rc != LDAP_SUCCESS )
			return 2;

		rc = ldap_search_ext_s(
				ld,		// LDAP session handle
				"o=Acme",	// Search Base
				LDAP_SCOPE_SUBTREE,	// Search Scope – everything below o=Acme
				"(objectClass=inetOrgPerson)", // Search Filter – only inetOrgPerson objects
				NULL,	// returnAllAttributes – NULL means Yes
				0,		// attributesOnly – False means we want values
				NULL,	// Server controls – There are none
				NULL,	// Client controls – There are none
				&timeOut,	// search Timeout
				LDAP_NO_LIMIT,	// no size limit
				&searchResult );
		if ( rc != LDAP_SUCCESS )
			return 3;

		for ( LDAPMessage *entry = ldap_first_entry( ld, searchResult );
			entry != NULL;
			entry = ldap_next_entry( ld, entry ) )
		{
			BerElement *ber;
			for ( attribute = ldap_first_attribute( ld, entry, &ber );
				attribute != NULL;
				attribute = ldap_next_attribute( ld, entry, ber ) )
			{
				for ( int i = 0; values[i] != NULL; ++i )
				{
					std::cout << attribute << ": " << values[i] << std::endl;
				}

				ldap_memfree( attribute );
			}
			ber_free( ber, 0 );
		}
		ldap_msgfree( searchResult );

		ldap_unbind_ext_s( ld, NULL, NULL );
		return( 0 );
	}

}

#endif // _KC_LDAPCONNECTION_H__KC_
